package com.lottemall.page.sevice;

import com.lottemall.item.pojo.*;
import com.lottemall.page.client.BrandClient;
import com.lottemall.page.client.CategoryClient;
import com.lottemall.page.client.GoodsClient;
import com.lottemall.page.client.SpecificationClient;
import com.netflix.discovery.converters.Auto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Slf4j
@Service
public class PageService {
    @Autowired
    private BrandClient brandClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specificationClient;

    /**
     * 注入模板引擎：为了实现页面的静态化
     */
    @Autowired
    private TemplateEngine templateEngine;

    public Map<String, Object> loadModel(Long spuId) {
        Map<String, Object> model = new HashMap<>();
        //查询spu
        Spu spu = goodsClient.querySpuById(spuId);
        //得到skus
        List<Sku> skus = spu.getSkus();
        //查询详情
        SpuDetail detail = spu.getSpuDetail();
        //查询brand
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        //查询商品分类
        List<Category> categories = categoryClient.queryByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        //查询规格组（内含规格参数）
        List<SpecGroup> specs = specificationClient.queryGroupByCid(spu.getCid3());


        model.put("spu", spu);
        model.put("skus", skus);
        model.put("detail", detail);
        model.put("brand", brand);
        model.put("categories", categories);
        model.put("specs", specs);
        return model;
    }

    /**
     * 为了实现页面的静态化
     */
    public void createHtml(Long spuId) {
        //得到上下文
        Context context = new Context();
        //存入数据
        context.setVariables(loadModel(spuId));
        //输出流
        File dest = new File("E:\\temp\\test\\upload", spuId + ".html");
        //首先判读是否存在，存在就删除，因为我们是要新建和修改结合
        if (dest.exists()) {
            dest.delete();
        }
        try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) {//jdk1.8新特性，而且这里还可以自动释放流
            //生成Html
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("[静态页服务] 生成静态页异常！" + e);
        }


    }

    /**
     * 删除静态页
     *
     * @param spuId 抽象商品id
     */
    public void deleteHtml(Long spuId) {
        File dest = new File("E:\\temp\\test\\upload", spuId + ".html");
        if (dest.exists()) {
            dest.delete();
        }
    }
}
